package com.tripcube.file.config;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 阿里云OSS配置信息
 */
@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssConfig {
    /**
     * 地域节点
     */
    private String endpoint;

    /**
     * 访问凭证key
     */
    private String accessKeyId;

    /**
     * 访问凭证密钥
     */
    private String accessKeySecret;

    /**
     * 存储桶名称
     */
    private String bucketName;

    /**
     * 协议类型 (http/https)
     */
    private String protocol = "http";

    /**
     * 最大重试次数
     */
    private int maxRetryCount = 3;

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public int getMaxRetryCount() {
        return maxRetryCount;
    }

    public void setMaxRetryCount(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }

    @Bean
    public OSS getOssClient() {
        // 创建客户端配置
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();

        // 设置协议
        if ("http".equalsIgnoreCase(protocol)) {
            conf.setProtocol(Protocol.HTTP);
        } else {
            conf.setProtocol(Protocol.HTTPS);
        }

        // 设置最大重试次数
        conf.setMaxErrorRetry(maxRetryCount);

        // 构建OSS客户端
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);
    }
}
